package com.javafm.jwt.helljwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    private String createToken(String username, String password) {
        return JWT.create().withAudience(username).sign(Algorithm.HMAC256(password));
    }


    @RequestMapping("/login")
    public Map<String, String> login(@RequestParam("username") String username, @RequestParam("password") String password) {
        if ("admin".equals(username) && "admin".equals(password)) {
            // 登录成功后创建jwt
            Map<String, String> resMap = new HashMap<>();
            resMap.put("token", createToken(username, password));
            resMap.put("code", "00000");
            resMap.put("msg", "success");
            return resMap;
        }
        Map<String, String> resMap = new HashMap<>();
        resMap.put("code", "A0200");
        resMap.put("msg", "用户登录异常");
        return resMap;
    }
}
